# db_web.pm
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information visit http://carrierclass.net/
#
use strict; use warnings;

package CCNCore::Provision::Database::CCNCore;
use base qw(CCNCore::Provision::JiftyDatabase);

use CCN::Text;
use CCNCore::Scripting;
use CCNCore::Home;

sub jifty_env($)
{
    my $self = shift;

    return
    {
        APPCLASS => 'CCNCore',
        APPNAME  => 'CCNCore',
        APPUUID  => 'FCBEA8AE-527B-11DC-B37F-B232495A851F',
    };
}

sub get_db_names() { return shift->p->get_provisioning_db_names }

sub grants($)
{
    my $self = shift;
    my $c    = shift;

    my ($DB_NAME) = $self->p->get_db_names();
    return unless defined $DB_NAME;

    # Grant access to the web scripts
    my $GRANTS = '';
    # YYYPORT www-data
    my $WEBUSER = 'www-data';

    my $SALT = $self->sql_get(<<'SQL',$self->p->{db_member});
    SELECT salt FROM systems WHERE id = (SELECT the_system FROM cluster WHERE id = ?)
SQL

    $self->sql_do_for(<<'SQL',
        SELECT server FROM provisioning_servers
SQL
    sub
    {
        my $CLIENT_pk = shift;
        my $CLIENT_IP = $self->get_replication_ip_of($CLIENT_pk);

        # See GUI.pm
        my $PASSWORD = $self->make_password(${SALT},${CLIENT_pk},"provision");

        $GRANTS .= <<"SQL";
GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${WEBUSER}'\@${CLIENT_IP} IDENTIFIED BY '${PASSWORD}';
SQL
    });

    foreach(CCNCore::Home::config."/local/bin/grants-web.sql")
    {
        print_to $c->root().$_, ${GRANTS};
        $c->commit_file($_);

        $self->log(ref($self)."::grants: run_command $DB_NAME $_\n"),
        CCN::Scripting::run_command(CCN::Scripting::sql::SQL_FILE(${DB_NAME}, $_))
            if $self->has_changed() or $c->changed($_);
    }
}

1;